
#include "../common/dynamic_ptr_arr.h"
#include "../common/mem.h"

dynamic_ptr_arr* dynamic_ptr_arr__allocate()
{
	return dynamic_ptr_arr__allocate_capacity(1);
}

dynamic_ptr_arr* dynamic_ptr_arr__allocate_capacity(int initial_capacity)
{
	dynamic_ptr_arr* arr;

	arr = mem_alloc_and_zero(1, sizeof(dynamic_ptr_arr));
	validate_allocation(arr, "the dynamic array");

	arr->capacity = initial_capacity;
	arr->values = mem_alloc(arr->capacity, sizeof(dynamic_ptr_arr_type));
	validate_allocation(arr->values, "the values buffer in the dynamic array");

	return arr;
}

void dynamic_ptr_arr__grow(dynamic_ptr_arr* arr)
{
	int previous_capacity;
	dynamic_ptr_arr_type* values_ptr;

	previous_capacity = arr->capacity;

	arr->capacity = previous_capacity * 2;
	values_ptr = arr->values;
	arr->values = mem_alloc(arr->capacity, sizeof(dynamic_ptr_arr_type));
	validate_allocation(arr->values, "a larger dynamic array");

	memcpy(arr->values, values_ptr, arr->count * sizeof(dynamic_ptr_arr_type));

	/*  Free old values array */
	mem_free(values_ptr);
}

void dynamic_ptr_arr__add(dynamic_ptr_arr* arr, dynamic_ptr_arr_type value)
{
	/*  Handle dynamic growth */
	if (arr->count == arr->capacity)
		dynamic_ptr_arr__grow(arr);

	/*  Add the value to the array and update the count */
	arr->values[arr->count++] = value;
}

void dynamic_ptr_arr__free(dynamic_ptr_arr* arr)
{
	mem_free(arr->values);
	mem_free(arr);
}

